package com.example.player.presentation.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Space;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.player.R;
import com.example.player.dao.viewmodel.SharedViewModel;
import com.example.player.domain.entity.Song;
import com.example.player.util.DataUtil;

import java.io.Serializable;
import java.util.List;

/**
 * 顶部导航栏，对应top_navigator
 * @author 朱文权
 * */
public class TopNavigatorFragment extends Fragment {
    /**
     * 共享数据
     * */
    private SharedViewModel shared;
    /**
     * 搜索按钮
     * */
    private ImageButton searchBtn;
    /**
     * 空白占位
     * */
    private Space space;
    /**
     * 取消搜索按钮
     * */
    private ImageButton close;
    /**
     * 搜索框
     * */
    private EditText search;
    /**
     * 菜单
     * */
    private ImageButton menu;
    /**
     * 现有的音乐
     * */
    private List<Song> songs;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.top_navigator,container,false);
        //绑定组件
        space=view.findViewById(R.id.space);
        close=view.findViewById(R.id.close);
        search=view.findViewById(R.id.search_frame);
        searchBtn =view.findViewById(R.id.ic_search);
        menu=view.findViewById(R.id.ic_menu_burger);
        //初始化shared
        shared=new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        //监听数据变化,及时更新数据
        shared.getLocalMusicSongs().observe(getViewLifecycleOwner(),songList->TopNavigatorFragment.this.songs=songList);
        //给搜索按钮添加监听器
        searchBtn.setOnClickListener(imgBtn->{
            //使空白符不可见，使搜索框和取消按钮可见
            space.setVisibility(View.GONE);
            close.setVisibility(View.VISIBLE);
            search.setVisibility(View.VISIBLE);
            //输入框获得焦点
            search.requestFocus();
            InputMethodManager imm = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(search, InputMethodManager.SHOW_IMPLICIT);
        });
        //给菜单添加监听器
        menu.setOnClickListener(imgBtn->{
            sendSongList(songs);
        });
        //对搜索框进行一些操作
        //文本变化监视器
        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //根据关键词模糊查询
                List<Song> query=DataUtil.query(songs,s.toString());
                //发送数据，渲染
                sendSongList(query);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //给close添加监视器
        close.setOnClickListener(cl->{
            if(search.hasFocus()){
                search.clearFocus();
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if(imm!=null){
                    //收起键盘
                    imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
                }
            }
            //清除search和close，恢复space
            search.setVisibility(View.GONE);
            search.setText("");
            close.setVisibility(View.GONE);
            space.setVisibility(View.VISIBLE);
            sendSongList(songs);
        });
        return view;
    }
    /**
     * 发送数据
     * */
    private void sendSongList(List<Song> songs){
        Bundle bundle=new Bundle();
        bundle.putSerializable("sendSongs",(Serializable) songs);
        getParentFragmentManager().setFragmentResult("TopNavigatorFragment",bundle);
    }
    /**
     * 优化返回键取消搜索框
     * */
    @Override
    public void onResume() {
        super.onResume();
        // 监听宿主 Activity 的返回键事件
        requireActivity().getOnBackPressedDispatcher().addCallback(
                getViewLifecycleOwner(),
                new OnBackPressedCallback(true) {
                    @Override
                    public void handleOnBackPressed() {
                        if (search.hasFocus()) {
                            InputMethodManager imm = (InputMethodManager) requireContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            if (imm.isActive(search)) {
                                //清除search和close，恢复space
                                search.setVisibility(View.GONE);
                                search.setText("");
                                close.setVisibility(View.GONE);
                                space.setVisibility(View.VISIBLE);
                                sendSongList(songs);
                                return; // 阻止返回键
                            }
                        }
                        // 允许默认返回键行为
                        setEnabled(false);
                        requireActivity().onBackPressed();
                    }
                }
        );
    }
}
